package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

//事务
type Doctor struct {
	id      int
	name    string
	age     int
	sex     int
	addTime string
}

func main() {
	db, err := sql.Open("mysql", "ding:dyw20020304@tcp(81.68.186.20:3306)/Ding?charset=utf8&parseTime=True")
	if err != nil {
		fmt.Println("sql.Open err = ", err)
		return
	}
	defer db.Close()
	tx, err := db.Begin() // 开启事务
	if err != nil {
		fmt.Println("db.Begin err = ", err)
		return
	}
	r1, _ := tx.Exec("update doctor_tb set age = age + 1  where name = ?", "丁杨维")
	r2, _ := tx.Exec("update doctor_tb set age = age + 1  where name = ?", "林医生")

	row1, _ := r1.RowsAffected()
	row2, _ := r2.RowsAffected()

	if row1 > 0 && row2 > 0 {
		//两个语句都成功才提交
		err := tx.Commit()
		if err != nil {
			fmt.Println("tx.Commit err = ", err)
			return
		}
		fmt.Println("tx.Commit succeed!")
	} else {
		//退回事务
		err := tx.Rollback()
		if err != nil {
			fmt.Println("tx.Rollback err = ", err)
			return
		}
		fmt.Println("tx.Rollback succeed!")
	}

}
